package com.gxuwz.stats.service.impl;

import com.alibaba.excel.EasyExcel;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.gxuwz.stats.entity.TotalWork;
import com.gxuwz.stats.entity.TotalWorkExcelDTO;
import com.gxuwz.stats.entity.User;
import com.gxuwz.stats.mapper.TotalWorkMapper;
import com.gxuwz.stats.service.TotalWorkService;
import com.gxuwz.stats.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import java.io.IOException;
import java.util.List;

@Service
public class TotalWorkServiceImpl extends ServiceImpl<TotalWorkMapper, TotalWork> implements TotalWorkService {

    @Autowired
    private TotalWorkMapper totalWorkMapper;
    @Autowired
    private UserService userService;

    /**
     * 分页查询并附加用户信息
     */
//    public IPage<TotalWork> getTotalWorkListWithUserInfo(IPage<TotalWork> page, QueryWrapper<TotalWork> queryWrapper) {
//        // 调用自定义 SQL 查询方法
//        return baseMapper.selectTotalWorkWithUsername(page, queryWrapper);
//    }
    public IPage<TotalWork> getTotalWorkListWithUserInfo(IPage<TotalWork> page, QueryWrapper<TotalWork> queryWrapper) {

        // 查询分页数据
        IPage<TotalWork> resultPage = this.page(page, queryWrapper);

        // 遍历分页结果，为每个 TotalWork 对象附加用户信息
        for (TotalWork totalWork : resultPage.getRecords()) {
            Integer userId = totalWork.getUserId();
            if (userId != null) {
                User user = userService.getById(userId);
                if (user != null) {
                    totalWork.setUsername(user.getUsername()); // 将用户名附加到 TotalWork 对象
                }
            }
        }
//        System.out.println("resultPage="+resultPage);
        return resultPage;
    }


    /**
     * 解析导入文件
     */
    public void importData(MultipartFile file) throws IOException {
        // 使用 EasyExcel 解析 Excel 文件
        List<TotalWork> dataList = EasyExcel.read(file.getInputStream())
                .head(TotalWork.class)
                .sheet()
                .doReadSync();

        for (TotalWork totalWork : dataList) {
            String username = totalWork.getUsername();
            String department = totalWork.getDepartment();

            // 如果 username 或 department 为空，则跳过当前记录
            if (username == null || username.trim().isEmpty() || department == null || department.trim().isEmpty()) {
                System.err.println("Skipping invalid record due to missing username or department.");
                continue;
            }

            try {
                // 获取或插入用户信息
                Integer userId = userService.getUserIdOrInsertUser(
                        username,
                        department,
                        totalWork.getDegree(),
                        totalWork.getPosition(),
                        totalWork.getPost()
                );

                // 设置用户ID
                totalWork.setUserId(userId);

                // 插入数据到 totalWork 表
                totalWorkMapper.insert(totalWork);
            } catch (Exception e) {
                // 记录异常情况以便后续分析
                System.err.println("Error processing user: " + username);
                e.printStackTrace();
            }
        }
    }

    public void saveAllFromDTO(List<TotalWork> dataList) {
        for (TotalWork totalWork : dataList) {
            String username = totalWork.getUsername();
            String department = totalWork.getDepartment();
            try {
                // 获取或插入用户信息
                Integer userId = userService.getUserIdOrInsertUser(
                        username,
                        department,
                        totalWork.getDegree(),
                        totalWork.getPosition(),
                        totalWork.getPost()
                );

                // 设置用户ID
                totalWork.setUserId(userId);

                // 插入数据到 totalWork 表
                totalWorkMapper.insert(totalWork);
            } catch (Exception e) {
                // 记录异常情况以便后续分析
                System.err.println("Error processing user: " + username);
                e.printStackTrace();
            }
        }
    }
}
